<template>
  <div class="station">
    <div class="search">
      <el-button
        type="primary"
        @click="addGroups(0)"
        plain="plain"
        class="addGroups"
        size="small"
        >添加职能组
      </el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="name" align="center" label="职能组名称">
      </el-table-column>
      <el-table-column prop="success" align="center" label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleExport(scope.row)"
            >成员管理</el-button
          >
          <el-button
            type="success"
            plain
            size="mini"
            @click="performance(scope.row)"
            >业绩属性管理</el-button
          >
          <el-button
            type="primary"
            plain
            size="mini"
            @click="addGroups(scope.row)"
            >修改</el-button
          >
          <el-button type="danger" plain size="mini" @click="remove(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 职能组弹框 -->
    <el-dialog
      :title="titleStation"
      :close-on-click-modal="false"
      :show-close="false"
      :visible.sync="dialogStation"
      width="500px"
      center
    >
      <el-form
        status-icon
        label-width="120px"
        :model="form"
        :rules="rules"
        ref="form"
        class="demo-ruleForm"
      >
        <el-form-item label="职能组名称" prop="name">
          <el-input
            v-model.trim="form.name"
            placeholder="请输入职能组名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-popover
            v-model="popoverVisible"
            placement="bottom"
            width="200"
            trigger="click"
          >
            <!-- click:点击select时弹出框显示 -->
            <!-- popover+tree用于选择，树形控件放在弹出框中 -->
            <el-tree
              :data="postData"
              :props="defaultPropss"
              :default-expand-all="true"
              show-checkbox
              @check="checkChange"
              ref="tree"
              node-key="id"
            />
            <!-- select展示选择结果，储存选择值typeValue -->
            <el-select
              slot="reference"
              class="elSelect"
              multiple
              collapse-tags
              v-model="typeValue"
              placeholder="请选择"
              :popper-append-to-body="false"
              popper-class="hiddenSel"
              v-default-select="[typeValue]"
              clearable
              @clear="clearTag"
              @remove-tag="removeTag"
            >
              <el-option
                v-for="item in optionData(postData)"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
          </el-popover>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close('form')">取 消</el-button>
        <el-button type="primary" @click="save('form')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 业绩属性弹框 -->
    <el-dialog
      title="业绩属性管理"
      :close-on-click-modal="false"
      :show-close="false"
      :visible.sync="dialogMance"
      width="500px"
      center
    >
      <el-tree
        :data="propertyList"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkTree"
        :props="defaultProps"
        ref="tree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogMance = false">取 消</el-button>
        <el-button type="primary" @click="beture">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import menuleft from "@/components/menuItem/menuleft.vue";
import {
  selectFunGroupList,
  deletePost,
  insertFunctionGroup,
  updateFunctionGroup,
  deleteFunctionGroup,
  selectAllFunctionAttr,
  selectGroupAttr,
  insertFunctionAttr,
  getdeptList,
} from "@/service/Api.js"; // 接口

export default {
  components: { menuleft },
  name: "companyMent",
  props: ["menuFlag"],
  data() {
    return {
      // 岗位管理
      dialogStation: false,
      popoverVisible: false,
      titleStation: "",
      tableData: [],
      name: "",
      form: {
        name: "",
        deptId: "",
      },
      rules: {},
      static: "",
      flag: "",
      id: "",
      fid: "",
      // 业绩
      formMance: {
        name: "",
      },
      dialogMance: false,
      propertyList: [],
      defaultProps: {
        label: "name",
      },
      defaultPropss: {
        children: "children",
        label: "name",
      },
      checkTree: [],
      selectedOptions: [], //部门绑定数组
      postData: [], //部门选择
      typeValue: [],
      typeLable: [],
    };
  },
  created() {
    this.selectFGList();
    this.getdept();
  },
  methods: {
    selectFGList() {
      selectFunGroupList().then((res) => {
        if (res.code === 0) {
          this.tableData = res.data;
        }
      });
    },
    // 部门列表树
    getdept() {
      getdeptList().then((res) => {
        if (res.code === 0) {
          this.treedata = [
            {
              name: "长沙豆子信息科技有限公司",
              id: "",
              children: res.data,
            },
          ];
          this.postData = this.TreeDataSource(res.data);
        }
      });
    },
    optionData(array, result = []) {
      array.forEach((item) => {
        result.push({ label: item.label, value: item.id });
        if (item.children && item.children.length !== 0) {
          this.optionData(item.children, result);
        }
      });
      return JSON.parse(JSON.stringify(result));
    },

    // tree选择值修改时
    checkChange() {
      this.typeValue = [];
      this.typeLable = [];
      // 将tree选择的id赋值给select
      this.$refs["tree"].getCheckedNodes().forEach((value) => {
        // 父级在select中不展示
        this.typeValue.push(value.id);
      });
    },
    // 清空select
    clearTag() {
      // 清空tree选择
      this.$refs["tree"].setCheckedKeys([]);
    },
    // 从select中单个移除时，保持tree选择值同步移除
    removeTag(data) {
      // 获取tree目前选择的值
      var chooseData = this.$refs["tree"].getCheckedNodes();
      var deleteIndex = "";
      // 找到chooseData中与清除的data相同的值
      chooseData.forEach((value, index) => {
        if (value === data) {
          deleteIndex = index;
        }
      });
      // 从tree目前选择值中去掉
      chooseData.splice(deleteIndex, 1);

      // 将修改后的值再赋给tree
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes(chooseData);
      });
    },

    // 递归替换属性名
    TreeDataSource(arr) {
      return arr.map((v, i) => {
        return {
          ...v,
          value: v.id,
          label: v.name,
          children: v.children ? this.TreeDataSource(v.children) : "",
        };
      });
    },
    //选择部门
    handleChoosedepartment(value) {
      // console.log(value);
    },
    handleCommon(name, row, idx) {
      if (this[name]) {
        this[name](row, idx);
      }
    },
    //成员管理
    handleExport(row) {
      // this.$router.push({ path: "/member", query: { id: row.id } });
      // console.log(row);
      this.$emit("toMember", row.id);
    },
    //删除-岗位和职能组
    remove(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          let url;
          console.log(row.upTime); //upTime-只存在职能组
          row.upTime
            ? (url = deleteFunctionGroup(row.id))
            : (url = deletePost(row.id));
          url.then((res) => {
            if (res.code == 0) {
              this.$message.success("删除成功!");
              this.selectFGList();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {});
    },
    //关闭弹框
    close(formName) {
      this.selectedOptions = [];
      this.typeValue = [];
      this.typeLable = [];
      this.$refs[formName].resetFields();
      this.dialogStation = false;
      this.$refs["tree"].setCheckedKeys([]);
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url;
          let opt = this.typeValue.join(",");
          if (this.typeLable.length) {
            opt = this.typeLable.join(",");
          }
          let data = {
            id: this.id,
            name: this.form.name,
            deptId: opt,
          };
          let data2 = {
            name: this.form.name,
            deptId: opt,
          };
          // this.static 0-岗位添加 1-岗位修改 2-职能组添加 3-职能组修改
          this.static == 2
            ? (url = insertFunctionGroup(data2))
            : (url = updateFunctionGroup(data));
          url.then((res) => {
            // console.log(res);
            if (res.code == 0) {
              this.selectFGList();
              this.$message.success("操作成功!");
              this.close("form");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 职能组--添加/修改
    addGroups(row) {
      this.flag = 1;
      if (row == 0) {
        this.titleStation = "添加职能组";
        this.static = 2;
        this.id = "";
        this.form.name = "";
      } else {
        this.titleStation = "修改职能组";
        this.static = 3;
        this.id = row.id;
        this.form.name = row.name;
        this.selectedOptions = row.deptId.split(",");
        this.typeValue = row.deptName.split(",");
        this.typeLable = row.deptId.split(",");
        let typeValue2 = [];
        this.typeValue.map((item, index) => {
          typeValue2.push({
            label: item,
            id: this.selectedOptions[index],
          });
        });
        this.$nextTick(() => {
          this.$refs.tree.setCheckedNodes(typeValue2);
        });
      }
      this.dialogStation = true;
    },
    // 业绩属性
    performance(row) {
      this.id = row.id;
      selectAllFunctionAttr().then((res) => {
        // console.log(res);
        if (res.code == 0) {
          this.propertyList = res.data;
          this.checkPer(row.id);
        }
      });
      this.dialogMance = true;
    },
    checkPer(id) {
      this.checkTree = [];
      selectGroupAttr(id).then((res) => {
        if (res.code == 0) {
          if (res.data.length > 0) {
            let arr = [];
            res.data.forEach((element, index) => {
              arr.push(element.id);
            });
            this.checkTree = arr;
          } else {
            this.checkTree = [];
          }
        }
      });
    },
    beture() {
      let keyList = this.$refs.tree.getCheckedKeys(true);
      console.log(keyList);
      insertFunctionAttr(this.id, keyList).then((res) => {
        // console.log(res);
        if (res.code == 0) {
          this.$message.success("操作成功~");
          this.dialogMance = false;
        }
      });
    },
  },
};
</script>

<style scoped>
.search span {
  display: flex;
  justify-content: space-between;
}

.addPost {
  margin-bottom: 15px;
}

.input-search,
.exit,
.addGroups {
  margin-bottom: 15px;
}

/* 把select的下拉框隐藏 */

.el-select {
  .el-select-dropdown.hiddenSel {
    display: none;
  }
}

.elSelect /deep/ .el-tag.el-tag--info .el-tag__close {
  display: none;
}
</style>
